/**
 * @file MQTTManager.cpp
 * @brief MQTT客户端管理类实现
 */

#include "MQTTManager.h"
#include "WiFiManager.h"
#include "DisplayManager.h"

extern WiFiManager wifiManager;
extern DisplayManager displayManager;

// 全局回调函数
static std::function<void()> displayRefreshCallback = nullptr;
static std::function<void(unsigned long)> sensorIntervalCallback = nullptr;
static std::function<void(unsigned long)> publishIntervalCallback = nullptr;
static std::function<void(unsigned long)> displayIntervalCallback = nullptr;  // 新增

void setDisplayRefreshCallback(std::function<void()> callback) {
    displayRefreshCallback = callback;
}

void setSensorIntervalCallback(std::function<void(unsigned long)> callback) {
    sensorIntervalCallback = callback;
}

void setPublishIntervalCallback(std::function<void(unsigned long)> callback) {
    publishIntervalCallback = callback;
}

// 新增屏幕间隔回调
void setDisplayIntervalCallback(std::function<void(unsigned long)> callback) {
    displayIntervalCallback = callback;
}

MQTTManager::MQTTManager() {
    lastReconnectAttempt = 0;
    mqttConnected = false;
    allowReconnect = true;

    // 设置默认MQTT服务器配置
    setDefaultServer();

    // 使用主题管理器生成客户端ID
    String clientId = topicManager.getDeviceId() + "_" + String(millis());
    mqttClient.setClientId(clientId.c_str());

    Serial.print("MQTT Client ID: ");
    Serial.println(clientId);

    // 设置回调函数
    mqttClient.onConnect([this](bool sessionPresent) {
        this->onMqttConnect(sessionPresent);
    });
    
    mqttClient.onDisconnect([this](AsyncMqttClientDisconnectReason reason) {
        this->onMqttDisconnect(reason);
    });
    
    mqttClient.onMessage([this](char* topic, char* payload, 
                               AsyncMqttClientMessageProperties properties, 
                               size_t len, size_t index, size_t total) {
        this->onMqttMessage(topic, payload, properties, len, index, total);
    });
    
    mqttClient.onSubscribe([this](uint16_t packetId, uint8_t qos) {
        this->onMqttSubscribe(packetId, qos);
    });
    
    mqttClient.onUnsubscribe([this](uint16_t packetId) {
        this->onMqttUnsubscribe(packetId);
    });
    
    mqttClient.onPublish([this](uint16_t packetId) {
        this->onMqttPublish(packetId);
    });
}

void MQTTManager::setMQTTServer(String server, int port, String user, String password) {
    mqttServer = server;
    mqttPort = port;
    mqttUser = user;
    mqttPassword = password;

    // 更新MQTT客户端配置
    mqttClient.setServer(mqttServer.c_str(), mqttPort);
    
    if (mqttUser.length() > 0 && mqttPassword.length() > 0) {
        mqttClient.setCredentials(mqttUser.c_str(), mqttPassword.c_str());
    } else {
        mqttClient.setCredentials("", "");  // 无认证
    }

    Serial.println("MQTT server configuration updated:");
    Serial.print("Server: "); Serial.println(mqttServer);
    Serial.print("Port: "); Serial.println(mqttPort);
    Serial.print("Username: "); Serial.println(mqttUser);
    Serial.print("Password: "); Serial.println(mqttPassword.length() > 0 ? "***" : "None");
}

void MQTTManager::setDefaultServer() {
    mqttServer = "test.mosquitto.org";
    mqttPort = 1883;
    mqttUser = "";
    mqttPassword = "";

    mqttClient.setServer(mqttServer.c_str(), mqttPort);
    mqttClient.setCredentials("", "");
}

bool MQTTManager::init() {
    if (!allowReconnect) {
        Serial.println("MQTT initialization failed: reconnection not allowed");
        return false;
    }

    Serial.println("Initializing AsyncMQTT client...");
    Serial.print("Connecting to: ");
    Serial.print(mqttServer);
    Serial.print(":");
    Serial.println(mqttPort);
    Serial.print("Device ID: ");
    Serial.println(topicManager.getDeviceId());

    // 检查WiFi连接状态
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("MQTT initialization failed: WiFi not connected");
        return false;
    }

    // 每次连接前重新生成客户端ID，避免重复
    String clientId = topicManager.getDeviceId() + "_" + String(millis());
    mqttClient.setClientId(clientId.c_str());

    Serial.print("Client ID: ");
    Serial.println(clientId);
    Serial.println("Starting MQTT connection...");

    // 先断开之前的连接（如果有）
    if (mqttClient.connected()) {
        mqttClient.disconnect(true);
        delay(100);
    }

    // 尝试连接MQTT服务器
    mqttClient.connect();

    Serial.println("MQTT connection request sent, waiting for result...");
    return true;
}

void MQTTManager::handleMQTT() {
    // AsyncMQTTClient是异步的，不需要在loop中处理
    // 所有操作都在回调函数中处理
}

void MQTTManager::onMqttConnect(bool sessionPresent) {
    Serial.println("=== MQTT Connection Successful ===");
    Serial.print("Device ID: ");
    Serial.println(topicManager.getDeviceId());
    Serial.print("Base Topic: ");
    Serial.println(topicManager.getBaseTopic());
    Serial.print("Session Present: ");
    Serial.println(sessionPresent);

    mqttConnected = true;

    // 订阅统一的命令和配置主题
    subscribe(topicManager.getCommandRequest().c_str());
    subscribe(topicManager.getConfigSet().c_str());
    subscribe(topicManager.getManagementRestart().c_str());

    // 发布连接状态
    publishConnectionStatus();

    Serial.println("MQTT topic subscription completed");

    // 通过回调通知显示刷新
    if (displayRefreshCallback) {
        displayRefreshCallback();
    }

    Serial.println("Display refresh notified");
}

void MQTTManager::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
    Serial.println("=== MQTT Connection Disconnected ===");
    Serial.print("Disconnect reason: ");

    switch (reason) {
        case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
            Serial.println("TCP connection disconnected");
            break;
        case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
            Serial.println("Unsupported MQTT protocol version");
            break;
        case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
            Serial.println("Client identifier rejected");
            break;
        case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE:
            Serial.println("Server unavailable");
            break;
        case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
            Serial.println("Invalid username or password");
            break;
        case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
            Serial.println("Not authorized");
            break;
        case AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT:
            Serial.println("TLS fingerprint error");
            break;
        default:
            Serial.println("Unknown reason");
            break;
    }

    Serial.print("Server: ");
    Serial.print(mqttServer);
    Serial.print(":");
    Serial.println(mqttPort);

    mqttConnected = false;

    // 通过回调通知显示刷新
    if (displayRefreshCallback) {
        displayRefreshCallback();
    }

    Serial.println("Display refresh notified");

    // 如果允许重连，尝试重新连接
    if (allowReconnect && !wifiManager.isInConfigMode()) {
        unsigned long currentMillis = millis();
        if (currentMillis - lastReconnectAttempt > 5000) {
            lastReconnectAttempt = currentMillis;
            Serial.println("Attempting to reconnect MQTT in 5 seconds...");
        }
    }
}

void MQTTManager::onMqttMessage(char* topic, char* payload, 
                               AsyncMqttClientMessageProperties properties, 
                               size_t len, size_t index, size_t total) {
    Serial.print("Received MQTT message [");
    Serial.print(topic);
    Serial.print("]: ");

    // 将payload转换为字符串
    String message;
    for (size_t i = 0; i < len; i++) {
        message += (char)payload[i];
    }
    Serial.println(message);

    // 如果在配置模式下，忽略所有MQTT消息
    if (wifiManager.isInConfigMode()) {
        Serial.println("Message ignored: device is in configuration mode");
        return;
    }

    // 解析JSON消息
    DynamicJsonDocument doc(1024);
    DeserializationError error = deserializeJson(doc, message);
    
    if (error) {
        Serial.print("JSON parsing error: ");
        Serial.println(error.c_str());
        return;
    }

    String command = doc["command"] | "";
    String requestId = doc["request_id"] | String(millis());

    // 根据主题路由消息
    if (strcmp(topic, topicManager.getCommandRequest().c_str()) == 0) {
        handleCommandRequest(doc, requestId);
    } else if (strcmp(topic, topicManager.getConfigSet().c_str()) == 0) {
        handleConfigSet(doc, requestId);
    } else if (strcmp(topic, topicManager.getManagementRestart().c_str()) == 0) {
        handleManagementCommand(doc, requestId);
    }
}

void MQTTManager::handleCommandRequest(JsonDocument& doc, String requestId) {
    String command = doc["command"] | "";
    Serial.println("Processing command request: " + command);

    DynamicJsonDocument responseDoc(1024);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = command;
    responseDoc["device_id"] = topicManager.getDeviceId();
    responseDoc["timestamp"] = millis();

    if (command == "get_status") {
        handleStatusQuery(requestId);
    } else if (command == "get_features") {
        handleFeatureStatusQuery(requestId);
    } else if (command == "display_control") {
        String state = doc["state"] | "";
        handleDisplayControl(state, requestId);
    } else if (command == "set_intervals") {
        unsigned long sensorInterval = doc["sensor_interval"] | 0;
        unsigned long publishInterval = doc["publish_interval"] | 0;
        unsigned long displayInterval = doc["display_interval"] | 0;  // 新增
        
        if (sensorInterval > 0) {
            handleIntervalControl("sensor", sensorInterval, requestId);
        }
        if (publishInterval > 0) {
            handleIntervalControl("publish", publishInterval, requestId);
        }
        if (displayInterval > 0) {  // 新增屏幕间隔处理
            handleIntervalControl("display", displayInterval, requestId);
        }
    } else if (command == "set_display_interval") {  // 新增独立命令
        unsigned long displayInterval = doc["interval"] | 0;
        handleIntervalControl("display", displayInterval, requestId);
    }else {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Unknown command";
        publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
    }
}

void MQTTManager::handleConfigSet(JsonDocument& doc, String requestId) {
    String command = doc["command"] | "";
    Serial.println("Processing configuration set: " + command);

    DynamicJsonDocument responseDoc(512);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = command;
    responseDoc["device_id"] = topicManager.getDeviceId();

    if (command == "enter_config_mode") {
        handleConfigModeCommand(requestId);
    } else {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Unknown configuration command";
        publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
    }
}

void MQTTManager::handleManagementCommand(JsonDocument& doc, String requestId) {
    String command = doc["command"] | "";
    Serial.println("Processing management command: " + command);

    if (command == "restart") {
        handleRestartCommand(requestId);
    }
}

// 具体命令实现
void MQTTManager::handleDisplayControl(String state, String requestId) {
    DynamicJsonDocument responseDoc(512);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = "display_control";
    responseDoc["device_id"] = topicManager.getDeviceId();

    if (state == "on" || state == "1" || state == "true") {
        setDisplayState(true);
        responseDoc["result"] = "success";
        responseDoc["message"] = "Display turned on";
        responseDoc["display_state"] = "on";
    } else if (state == "off" || state == "0" || state == "false") {
        setDisplayState(false);
        responseDoc["result"] = "success";
        responseDoc["message"] = "Display turned off";
        responseDoc["display_state"] = "off";
    } else if (state == "toggle") {
        bool currentState = displayManager.isDisplayOn();
        setDisplayState(!currentState);
        responseDoc["result"] = "success";
        responseDoc["message"] = "Display toggled";
        responseDoc["display_state"] = !currentState ? "on" : "off";
    } else {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Invalid display state";
    }

    publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
}

void MQTTManager::handleIntervalControl(String type, unsigned long interval, String requestId) {
    DynamicJsonDocument responseDoc(512);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = "set_" + type + "_interval";
    responseDoc["device_id"] = topicManager.getDeviceId();

    // 验证间隔值有效性
    if (interval < 100) {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Interval too short, minimum 100ms";
        publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
        return;
    }

    if (interval > 3600000 && type != "display") {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Interval too long, maximum 3600000ms";
        publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
        return;
    }
    
    // 屏幕间隔特殊限制
    if (type == "display" && interval > 60000) {
        responseDoc["result"] = "error";
        responseDoc["message"] = "Display interval too long, maximum 60000ms";
        publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
        return;
    }

    if (type == "sensor") {
        setSensorReadInterval(interval);
        if (sensorIntervalCallback) {
            sensorIntervalCallback(interval);
        }
        responseDoc["result"] = "success";
        responseDoc["message"] = "Sensor interval updated";
        responseDoc["sensor_interval"] = interval;
        Serial.print("Sensor interval set to: ");
        Serial.println(interval);
    } else if (type == "publish") {
        setPublishInterval(interval);
        if (publishIntervalCallback) {
            publishIntervalCallback(interval);
        }
        responseDoc["result"] = "success";
        responseDoc["message"] = "Publish interval updated";
        responseDoc["publish_interval"] = interval;
        Serial.print("Publish interval set to: ");
        Serial.println(interval);
    } else if (type == "display") {  // 新增屏幕间隔处理
        setDisplayInterval(interval);
        responseDoc["result"] = "success";
        responseDoc["message"] = "Display interval updated";
        responseDoc["display_interval"] = interval;
        Serial.print("Display interval set to: ");
        Serial.println(interval);
        
        // 调用回调函数更新主循环变量
        if (displayIntervalCallback) {
            displayIntervalCallback(interval);
        }
    }

    // 保存当前所有间隔配置到EEPROM
    unsigned long currentSensorInterval = getSensorReadInterval();
    unsigned long currentPublishInterval = getPublishInterval();
    unsigned long currentDisplayInterval = getDisplayInterval();
    
    // 根据类型更新对应的间隔
    if (type == "sensor") {
        currentSensorInterval = interval;
    } else if (type == "publish") {
        currentPublishInterval = interval;
    } else if (type == "display") {
        currentDisplayInterval = interval;
    }
    
    // 保存到EEPROM
    wifiManager.saveIntervalConfig(currentSensorInterval, currentPublishInterval, currentDisplayInterval);

    publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
}

void MQTTManager::handleStatusQuery(String requestId) {
    DynamicJsonDocument doc(1024);
    doc["request_id"] = requestId;
    doc["command"] = "get_status";
    doc["device_id"] = topicManager.getDeviceId();
    doc["timestamp"] = millis();
    
    // WiFi状态
    doc["wifi_connected"] = (WiFi.status() == WL_CONNECTED);
    doc["wifi_ssid"] = WiFi.SSID();
    doc["wifi_rssi"] = WiFi.RSSI();
    doc["ip_address"] = WiFi.localIP().toString();
    
    // MQTT状态
    doc["mqtt_connected"] = isConnected();
    doc["mqtt_server"] = mqttServer;
    doc["mqtt_port"] = mqttPort;
    
    // 系统状态
    doc["free_heap"] = ESP.getFreeHeap();
    doc["uptime"] = millis();
    
    doc["result"] = "success";
    
    publishJsonMessage(topicManager.getCommandResponse().c_str(), doc);
}

void MQTTManager::handleFeatureStatusQuery(String requestId) {
    DynamicJsonDocument doc(1024);
    doc["request_id"] = requestId;
    doc["command"] = "get_features";
    doc["device_id"] = topicManager.getDeviceId();
    doc["timestamp"] = millis();
    
    // 功能状态
    doc["display_state"] = displayManager.isDisplayOn() ? "on" : "off";
    doc["sensor_interval"] = getSensorReadInterval();
    doc["publish_interval"] = getPublishInterval();
    doc["display_interval"] = getDisplayInterval();  // 新增
    doc["sensor_available"] = true; // 需要从传感器管理器获取实际状态
    
    // 系统信息
    doc["firmware_version"] = "1.0.0";
    doc["chip_model"] = "ESP32";
    doc["free_heap"] = ESP.getFreeHeap();
    
    doc["result"] = "success";
    
    publishJsonMessage(topicManager.getCommandResponse().c_str(), doc);
}

void MQTTManager::handleRestartCommand(String requestId) {
    DynamicJsonDocument responseDoc(512);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = "restart";
    responseDoc["device_id"] = topicManager.getDeviceId();
    responseDoc["result"] = "success";
    responseDoc["message"] = "Device restarting";
    
    publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
    
    // 延迟确保消息发送
    delay(2000);
    
    Serial.println("Received restart command, device restarting...");
    ESP.restart();
}

void MQTTManager::handleConfigModeCommand(String requestId) {
    DynamicJsonDocument responseDoc(512);
    responseDoc["request_id"] = requestId;
    responseDoc["command"] = "enter_config_mode";
    responseDoc["device_id"] = topicManager.getDeviceId();
    responseDoc["result"] = "success";
    responseDoc["message"] = "Entering configuration mode";
    
    publishJsonMessage(topicManager.getCommandResponse().c_str(), responseDoc);
    
    // 停止MQTT自动重连
    stopReconnect();
    
    // 清空WiFi凭证
    wifiManager.clearWiFiCredentials();
    
    // 断开MQTT连接
    disconnect();
    
    // 延迟确保消息已发送
    delay(2000);
    
    Serial.println("WiFi credentials cleared, starting configuration mode...");
    
    // 直接启动配置模式
    if (wifiManager.startConfigMode()) {
        Serial.println("Configuration mode started successfully");
    } else {
        Serial.println("Configuration mode startup failed");
        // 如果配置模式启动失败，重新允许MQTT重连
        allowReconnections();
    }
}

// 发布连接状态
void MQTTManager::publishConnectionStatus() {
    DynamicJsonDocument doc(512);
    doc["device_id"] = topicManager.getDeviceId();
    doc["wifi_ssid"] = WiFi.SSID();
    doc["wifi_rssi"] = WiFi.RSSI();
    doc["ip_address"] = WiFi.localIP().toString();
    doc["mqtt_server"] = mqttServer;
    doc["mqtt_connected"] = true;
    doc["timestamp"] = millis();
    
    publishJsonMessage(topicManager.getTelemetryNetwork().c_str(), doc);
}

// 设置和获取方法实现
void MQTTManager::setSensorReadInterval(unsigned long interval) {
    extern unsigned long sensorReadInterval;
    sensorReadInterval = interval;
}

void MQTTManager::setPublishInterval(unsigned long interval) {
    extern unsigned long publishInterval;
    publishInterval = interval;
}

unsigned long MQTTManager::getSensorReadInterval() {
    extern unsigned long sensorReadInterval;
    return sensorReadInterval;
}

unsigned long MQTTManager::getPublishInterval() {
    extern unsigned long publishInterval;
    return publishInterval;
}

void MQTTManager::setDisplayState(bool state) {
    if (state) {
        displayManager.turnOn();
    } else {
        displayManager.turnOff();
    }

    // 通知显示刷新
    if (displayRefreshCallback) {
        displayRefreshCallback();
    }
}

bool MQTTManager::getDisplayState() {
    return displayManager.isDisplayOn();
}

String MQTTManager::getFeatureStatus() {
    String status = "{";
    status += "\"display_state\":\"" + String(displayManager.isDisplayOn() ? "on" : "off") + "\",";
    status += "\"sensor_interval\":" + String(getSensorReadInterval()) + ",";
    status += "\"publish_interval\":" + String(getPublishInterval()) + ",";
    status += "\"wifi_connected\":" + String(WiFi.status() == WL_CONNECTED ? "true" : "false") + ",";
    status += "\"mqtt_connected\":" + String(isConnected() ? "true" : "false") + ",";
    status += "\"sensor_found\":" + String(true ? "true" : "false") + ",";
    status += "\"free_heap\":" + String(ESP.getFreeHeap());
    status += "}";

    return status;
}

void MQTTManager::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
    Serial.print("Subscribe acknowledged, PacketId: ");
    Serial.println(packetId);
}

void MQTTManager::onMqttUnsubscribe(uint16_t packetId) {
    Serial.print("Unsubscribe acknowledged, PacketId: ");
    Serial.println(packetId);
}

void MQTTManager::onMqttPublish(uint16_t packetId) {
    Serial.print("Message publish acknowledged, PacketId: ");
    Serial.println(packetId);
}

void MQTTManager::reconnect() {
    if (!allowReconnect) {
        return;
    }

    Serial.println("Attempting to reconnect to MQTT server...");

    // 如果已经连接，先断开
    if (mqttClient.connected()) {
        mqttClient.disconnect();
    }

    // 重新连接
    mqttClient.connect();
}

void MQTTManager::publishSensorData(float temperature, float humidity, int rssi) {
    if (!isConnected()) {
        Serial.println("Cannot publish sensor data: MQTT not connected");
        return;
    }

    DynamicJsonDocument doc(256);
    doc["device_id"] = topicManager.getDeviceId();
    doc["temperature"] = temperature;
    doc["humidity"] = humidity;
    doc["rssi"] = rssi;
    doc["timestamp"] = millis();

    publishJsonMessage(topicManager.getTelemetrySensor().c_str(), doc);
}

void MQTTManager::publishMessage(const char* topic, const char* message) {
    if (!isConnected()) {
        Serial.println("Cannot publish message: MQTT not connected");
        return;
    }

    uint16_t packetId = mqttClient.publish(topic, 1, true, message);

    if (packetId > 0) {
        Serial.print("Message published successfully [");
        Serial.print(topic);
        Serial.print("]: ");
        Serial.println(message);
    } else {
        Serial.println("Message publish failed");
    }
}

void MQTTManager::publishJsonMessage(const char* topic, JsonDocument& doc) {
    if (!isConnected()) {
        Serial.println("Cannot publish JSON message: MQTT not connected");
        return;
    }

    String payload;
    serializeJson(doc, payload);

    uint16_t packetId = mqttClient.publish(topic, 1, true, payload.c_str());

    if (packetId > 0) {
        Serial.print("JSON message published successfully [");
        Serial.print(topic);
        Serial.print("]: ");
        serializeJson(doc, Serial);
        Serial.println();
    } else {
        Serial.println("JSON message publish failed");
    }
}

void MQTTManager::subscribe(const char* topic) {
    uint16_t packetId = mqttClient.subscribe(topic, 1);

    if (packetId > 0) {
        Serial.print("Topic subscribed successfully: ");
        Serial.println(topic);
    } else {
        Serial.print("Topic subscription failed: ");
        Serial.println(topic);
    }
}

void MQTTManager::unsubscribe(const char* topic) {
    uint16_t packetId = mqttClient.unsubscribe(topic);

    if (packetId > 0) {
        Serial.print("Topic unsubscribed successfully: ");
        Serial.println(topic);
    } else {
        Serial.print("Topic unsubscription failed: ");
        Serial.println(topic);
    }
}

void MQTTManager::disconnect() {
    Serial.println("Disconnecting MQTT...");
    mqttClient.disconnect(true);
    mqttConnected = false;
}

bool MQTTManager::isConnected() {
    bool connected = mqttConnected && mqttClient.connected();

    // 调试信息
    static unsigned long lastDebug = 0;
    static bool lastState = false;
    unsigned long currentMillis = millis();

    if (currentMillis - lastDebug >= 10000) {
        lastDebug = currentMillis;
        if (connected != lastState) {
            Serial.print("[MQTT Status Change] New state: ");
            Serial.println(connected ? "Connected" : "Disconnected");
            lastState = connected;
        }
    }

    return connected;
}

void MQTTManager::stopReconnect() {
    Serial.println("Stopping MQTT auto-reconnect");
    allowReconnect = false;
    disconnect();
}

void MQTTManager::allowReconnections() {
    Serial.println("Allowing MQTT auto-reconnect");
    allowReconnect = true;
}

bool MQTTManager::testServerConnectivity() {
    Serial.println("Testing MQTT server connectivity...");

    WiFiClient testClient;

    // 解析域名获取IP地址
    IPAddress ip;
    if (WiFi.hostByName(mqttServer.c_str(), ip)) {
        Serial.print("Resolved server IP: ");
        Serial.println(ip);

        // 检查是否是IPv6地址
        if (ip.toString().indexOf(':') >= 0) {
            Serial.println("Warning: Resolved to IPv6 address, ESP32 may not be able to connect");
        }
    } else {
        Serial.println("Domain name resolution failed");
        return false;
    }

    // 使用IP地址连接，而不是域名
    if (testClient.connect(ip, mqttPort)) {
        Serial.println("MQTT server TCP connectivity test successful");
        testClient.stop();
        return true;
    } else {
        Serial.println("MQTT server TCP connectivity test failed");
        return false;
    }
}

void MQTTManager::fullReset() {
    Serial.println("=== MQTT Client Full Reset ===");

    // 停止自动重连
    stopReconnect();

    // 断开连接
    disconnect();

    // 重置内部状态
    mqttConnected = false;
    lastReconnectAttempt = 0;

    // 重新生成客户端ID
    String clientId = topicManager.getDeviceId() + "_" + String(millis());
    mqttClient.setClientId(clientId.c_str());

    Serial.print("Client ID after reset: ");
    Serial.println(clientId);

    // 重新允许重连
    allowReconnections();

    Serial.println("MQTT client reset completed");
}

String MQTTManager::getConnectionStatus() {
    String status = "MQTT Status: ";

    if (mqttConnected && mqttClient.connected()) {
        status += "Connected (";
        status += mqttServer;
        status += ":";
        status += mqttPort;
        status += ")";
    } else if (mqttConnected && !mqttClient.connected()) {
        status += "Connecting...";
    } else if (!mqttConnected && mqttClient.connected()) {
        status += "State inconsistent (client connected but internal state not updated)";
    } else {
        status += "Disconnected";
    }

    return status;
}

void MQTTManager::setDisplayInterval(unsigned long interval) {
    displayManager.setDisplayInterval(interval);
}

unsigned long MQTTManager::getDisplayInterval() {
    return displayManager.getDisplayInterval();
}